package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * @author 赵红娇
 * @date 2020年8月9日上午9:23:34
 */
public class JDBCUtil {
	private static final String DRIVER="com.mysql.jdbc.Driver";
	private static final String URL="jdbc:mysql://localhost:3306/restaurant_ordering";
	private static final String USER="root";
	private static final String PASSWORD="root";
	static {
		try {
			Class.forName(DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} 
	}
	public static Connection getConn() {
		Connection conn=null;
		try {
			conn=DriverManager.getConnection(URL,USER,PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	public static void closeConn(ResultSet rs,PreparedStatement ps,Connection conn) {
		try {
			if(rs!=null) {
				rs.close();
				rs=null;
			}
			if(ps!=null) {
				ps.close();
				ps=null;
			}
			if(conn!=null) {
				conn.close();
				conn=null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	public static int executeUpdate(String sql,Object...params) {
		int num=0;
		Connection conn=null;
		PreparedStatement ps=null;
		try {
			conn = getConn();
			ps = conn.prepareStatement(sql);
			if(params!=null) {
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i+1, params[i]);
				}
			}
			num=ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.closeConn(null, ps, conn);
		}
		return num;
	}
	public static <T> List<T> executeQuery(String sql,ResultSetCreateObject<T> rco,Object...params){
		List<T> list=new ArrayList<>();
		Connection conn = JDBCUtil.getConn();
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			ps = conn.prepareStatement(sql);
			if(params!=null) {
				for (int i = 0; i < params.length; i++) {
					ps.setObject(i+1, params[i]);
				}
			}
			rs=ps.executeQuery();
			while(rs.next()) {
				list.add(rco.create(rs));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			JDBCUtil.closeConn(rs, ps, conn);
		}
		return list;
	}
	public static <T> List<T> executeQuery(String sql,ResultSetCreateObject<T> rco){
		List<T> list=new ArrayList<>();
		Connection conn=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		conn=getConn();
		try {
			ps=conn.prepareStatement(sql);
			rs=ps.executeQuery();
			while(rs.next()) {
				T t = rco.create(rs);
				list.add(t);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			closeConn(rs, ps, conn);
		}
		return list;
	}
}
